from pykeyboard import PyKeyboardEvent
from pykeyboard import PyKeyboard
from threading import Thread
import time
import os

'''
    ctrl+F8--->开始
    ctrl+F7--->结束
    想干的事写在mydo()里面即可
'''

isStart = False
isEnd = False


class MyPyKeyboardEvent(PyKeyboardEvent):

    def __init__(self):
        PyKeyboardEvent.__init__(self)
        self.isF7Press = False
        self.isF8Press = False
        self.isLeftctrlPress = False
        self.isLeftaltPress = False
        self.isLeftshiftPress = False

    def tap(self, keycode, character, press):
        # print(keycode, character, press)
        if character == 'LCONTROL':
            if press == True:
                self.isLeftctrlPress = True
            else:
                self.isLeftctrlPress = False

        if character == 'LMENU':
            if press == True:
                self.isLeftaltPress = True
            else:
                self.isLeftaltPress = False

        if character == 'LSHIFT':
            if press == True:
                self.isLeftshiftPress = True
            else:
                self.isLeftshiftPress = False

        if character == 'F8':
            if press == True:
                self.isF8Press = True
            else:
                self.isF8Press = False

        if character == 'F7':
            if press == True:
                self.isF7Press = True
            else:
                self.isF7Press = False

        # ctrl+F8
        if self.isF8Press == True and self.isLeftctrlPress == True and self.isLeftaltPress == True and self.isLeftshiftPress == True:
            global isStart
            isStart = True

        # ctrl+F7
        if self.isF7Press == True and self.isLeftctrlPress == True:
            global isEnd
            isEnd = True


def mydo():
    # dotimes(doOne, 5, 0.5)
    dotimes(doRename, 5, 0.5)


def doOne():
    print('shuoGG')


def doRename():
    global keyBoard
    time.sleep(1)
    # keyBoard.tap_key(keyBoard.function_keys[2])     # F2
    keyBoard.type_string('newname1')                # type a string
    keyBoard.tap_key(keyBoard.down_key)               # 方向键下

# 以intervals时间间隔干times次func


def dotimes(func, times, intervals):
    for x in range(0, times):
        func()
        if intervals != 0:
            time.sleep(intervals)


def startwork():
    global isStart
    print('-------------------start------------------')
    while True:
        if isStart:
            isStart = False
            mydo()
        time.sleep(0.01)


def exitwork():
    global isEnd
    while True:
        if isEnd:
            print('-------------------end------------------')
            os._exit(0)

keyBoard = PyKeyboard()
thread1 = Thread(target=startwork)
thread1.start()
thread2 = Thread(target=exitwork)
thread2.start()
p = MyPyKeyboardEvent()
p.run()
